package concurrent.aqs.share;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 在缓存系统中，多个线程可能同时需要读取缓存中的数据。为了避免数据不一致和提高并发访问效率，可以使用共享锁来控制对缓存的读取操作。
 * 当多个线程读取缓存时，它们可以同时获取共享锁；而当需要更新缓存时，则需要获取独占锁。
 */
public class CacheSystem {
    private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    private final ReentrantReadWriteLock.ReadLock readLock = rwLock.readLock();
    private final ReentrantReadWriteLock.WriteLock writeLock = rwLock.writeLock();
    private final Map<String, Object> cache = new HashMap<>();

    public Object getFromCache(String key) {
        readLock.lock();
        try {
            return cache.get(key);
        } finally {
            readLock.unlock();
        }
    }

    public void putIntoCache(String key, Object value) {
        writeLock.lock();
        try {
            cache.put(key, value);
        } finally {
            writeLock.unlock();
        }
    }
}